<template>
    <div class="question-detail-container">
      <!-- 面包屑导航
      <el-breadcrumb class="breadcrumb" separator="/">
        <el-breadcrumb-item :to="{ path: '/question' }">题库</el-breadcrumb-item>
        <el-breadcrumb-item>{{ route.query.libraryName }}</el-breadcrumb-item>
      </el-breadcrumb> -->
  
      <!-- 顶部操作区域 -->
      <div class="top-actions">
        <div class="left-actions">
          <el-select v-model="selectValue" class="filter-select" @change="filterQuestions">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
  
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>添加题目
          </el-button>
  
          <el-button @click="exportToWord" :loading="exporting">
            <el-icon><Document /></el-icon>导出Word
          </el-button>
        </div>
        
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索题目内容"
            class="search-input"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>
  
      <!-- 题目列表区域 -->
      <div class="questions-list">
        <el-card 
          v-for="(question, index) in filteredQuestions" 
          :key="question.id"
          class="question-card"
          shadow="hover"
        >
          <!-- 添加编辑图标 -->
          <div class="edit-icon">
            <el-tooltip
              content="编辑题目"
              placement="top"
              :hide-after="0"
            >
              <el-icon @click="handleEdit(question)" class="edit-btn">
                <Edit />
              </el-icon>
            </el-tooltip>
            <el-tooltip
              content="删除题目"
              placement="top"
              :hide-after="0"
            >
              <el-icon @click="handleDelete(question)" class="delete-btn">
                <Delete />
              </el-icon>
            </el-tooltip>
          </div>
  
  
          <!-- 题目头部 -->
          <div class="question-header">
            <span class="question-index">第 {{ index + 1 }} 题</span>
            <el-tag 
              :type="getQuestionTypeTag(question.questionType)" 
              effect="light" 
              class="question-type-tag"
            >
              {{ getQuestionTypeLabel(question.questionType) }}
            </el-tag>
            <el-tag 
              :type="getDifficultyTag(question.difficulty)" 
              effect="light" 
              size="small" 
              class="difficulty-tag"
            >
              {{ getDifficultyLabel(question.difficulty) }}
            </el-tag>
          </div>
  
          <!-- 题目内容 -->
          <div class="question-content">
            <!-- 综合题文章内容 -->
            <div v-if="question.questionType === 'READING'" class="reading-passage">
              <div class="passage-content">{{ question.passage }}</div>
              <!-- 综合题子题目 -->
              <div v-if="question.subQuestions" class="sub-questions">
                <div v-for="(subQ, index) in question.subQuestions" :key="subQ.id" class="sub-question">
                  <div class="sub-question-header">
                    <span class="sub-question-index">第{{ index + 1 }}小题</span>
                    <span class="sub-question-score">({{ subQ.score }}分)</span>
                  </div>
                  <div class="sub-question-stem">{{ subQ.stem }}</div>
                  <!-- 子题目选项 -->
                  <div v-if="subQ.options && subQ.options.length > 0" class="sub-question-options">
                    <div v-for="option in subQ.options" :key="option.optionId" class="option-item">
                      <span class="option-id">{{ option.optionId }}.</span>
                      <span class="option-content">{{ option.content }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
  
            <!-- 非综合题题目的题干 -->
            <div v-else class="question-stem">{{ question.stem }}</div>
  
            <!-- 选项区域 - 单选和多选 -->
            <div v-if="['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(question.questionType)" class="options-list">
              <div v-for="option in question.options" :key="option.optionId" class="option-item">
                <span class="option-id">{{ option.optionId }}.</span>
                <span class="option-content">{{ option.content }}</span>
              </div>
            </div>
  
            <!-- 判断题 -->
            <div v-if="question.questionType === 'TRUE_FALSE'" class="true-false-options">
              <el-radio-group v-model="question.userAnswer" disabled>
                <el-radio label="TRUE">正确</el-radio>
                <el-radio label="FALSE">错误</el-radio>
              </el-radio-group>
            </div>
  
            <!-- 填空题 -->
            <div v-if="question.questionType === 'FILL_BLANK'" class="fill-blank-content">
              <!-- <div class="fill-blank-stem">
                {{ formatFillBlankStem(question.stem) }}
              </div> -->
              <div class="fill-blank-answers">
                <div v-for="(blank, index) in question.blanks?.split('|')" :key="index" class="blank-item">
                  <span class="blank-index">第{{ index + 1 }}空：</span>
                  <span class="blank-answer">{{ blank }}</span>
                </div>
              </div>
            </div>
          </div>
  
          <!-- 答案和解析区域 -->
          <el-collapse class="answer-section">
            <el-collapse-item>
              <template #title>
                <span class="answer-title">答案与解析</span>
              </template>
              <div class="answer-content">
                <!-- 答案展示 -->
                <div class="answer-area">
                  <strong>答案：</strong>
                  <template v-if="question.questionType === 'SINGLE_CHOICE'">
                    {{ question.answer }}
                  </template>
                  <template v-else-if="question.questionType === 'MULTIPLE_CHOICE'">
                    {{ question.answers?.[0] }}
                  </template>
                  <template v-else-if="question.questionType === 'TRUE_FALSE'">
                    {{ question.answer === 'TRUE' ? '正确' : '错误' }}
                  </template>
                  <template v-else-if="question.questionType === 'FILL_BLANK'">
                    <div v-for="(blank, index) in question.blanks?.split('|')" :key="index" class="blank-answer-item">
                      <span>第{{ index + 1 }}空：{{ blank }}</span>
                    </div>
                  </template>
                  <template v-else-if="question.questionType === 'READING'">
                    <div v-for="(subQ, index) in question.subQuestions" :key="subQ.id" class="sub-question-answer">
                      <div class="sub-question-title">第{{ index + 1 }}小题：</div>
                      <div class="sub-question-content">{{ subQ.answer }}</div>
                    </div>
                  </template>
                  <template v-else>
                    <div class="formatted-answer">{{ question.answers?.[0] || question.answer }}</div>
                  </template>
                </div>
  
                <!-- 解析展示 -->
                <div class="analysis-area" v-if="question.analysis || (question.questionType === 'READING' && question.subQuestions)">
                  <strong>解析：</strong>
                  <template v-if="question.questionType === 'READING'">
                    <div v-for="(subQ, index) in question.subQuestions" :key="subQ.id" class="sub-question-analysis">
                      <div class="sub-question-title">第{{ index + 1 }}小题：</div>
                      <div class="sub-question-content">{{ subQ.analysis }}</div>
                    </div>
                  </template>
                  <template v-else>
                    <div class="analysis-content">{{ question.analysis }}</div>
                  </template>
                </div>
  
                <!-- 知识点标签 -->
                <div class="knowledge-points" v-if="question.knowledgePoints?.length">
                  <strong>知识点：</strong>
                  <el-tag
                    v-for="point in question.knowledgePoints"
                    :key="point"
                    class="knowledge-tag"
                    effect="plain"
                    size="small"
                  >
                    {{ point }}
                  </el-tag>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </div>
  
      <!-- 添加编辑抽屉 -->
      <el-drawer
        v-model="dialogVisible"
        :title="editForm.id ? '编辑题目' : '添加题目'"
        direction="rtl"
        size="40%"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        class="edit-drawer"
      >
        <template #default>
          <el-form
            ref="editFormRef"
            :model="editForm"
            :rules="rules"
            label-width="100px"
            class="edit-form"
          >
            <!-- 题型 -->
            <el-form-item label="题目类型" prop="questionType">
              <el-select v-model="editForm.questionType" :disabled="disabled" class="form-select">
                <el-option
                  v-for="item in options.filter(item => item.value !== 'all')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
  
            <!-- 题干 -->
            <el-form-item label="题目内容" prop="stem">
              <template v-if="editForm.questionType === 'READING'">
                <el-input
                  v-model="editForm.passage"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入阅读文章内容"
                />
              </template>
              <template v-else>
                <el-input
                  v-model="editForm.stem"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入题目内容"
                />
              </template>
            </el-form-item>
  
            <!-- 选项（单选和多选题） -->
            <template v-if="['SINGLE_CHOICE', 'MULTIPLE_CHOICE'].includes(editForm.questionType)">
              <el-form-item
                v-for="(option, index) in editForm.options"
                :key="index"
                :label="'选项' + option.optionId"
                :prop="'options.' + index + '.content'"
                :rules="{ required: true, message: '选项内容不能为空', trigger: 'blur' }"
              >
                <div class="option-edit">
                  <el-input v-model="option.content" placeholder="请输入选项内容" />
                  <el-button
                    type="danger"
                    circle
                    @click="removeOption(index)"
                    :disabled="editForm.options.length <= 2"
                    class="remove-btn"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  plain
                  @click="addOption"
                  :disabled="editForm.options.length >= 6"
                >
                  添加选项
                </el-button>
              </el-form-item>
            </template>
  
            <!-- 答案 -->
            <el-form-item label="答案" prop="answer">
              <template v-if="editForm.questionType === 'SINGLE_CHOICE'">
                <el-select v-model="editForm.answer" class="form-select">
                  <el-option
                    v-for="option in editForm.options"
                    :key="option.optionId"
                    :label="option.optionId"
                    :value="option.optionId"
                  />
                </el-select>
              </template>
              <template v-else-if="editForm.questionType === 'MULTIPLE_CHOICE'">
                <el-select
                  v-model="editForm.answers_tmp"
                  multiple
                  class="form-select"
                  @change="handleMultipleAnswerChange"
                >
                  <el-option
                    v-for="option in editForm.options"
                    :key="option.optionId"
                    :label="option.optionId"
                    :value="option.optionId"
                  />
                </el-select>
              </template>
              <template v-else-if="editForm.questionType === 'TRUE_FALSE'">
                <el-radio-group v-model="editForm.answer">
                  <el-radio label="TRUE">正确</el-radio>
                  <el-radio label="FALSE">错误</el-radio>
                </el-radio-group>
              </template>
              <template v-else>
                <el-input
                  v-model="editForm.answers[0]"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入答案"
                />
              </template>
            </el-form-item>
  
            <!-- 难度 -->
            <el-form-item label="难度" prop="difficulty">
              <el-select v-model="editForm.difficulty" class="form-select">
                <el-option label="简单" :value="1" />
                <el-option label="中等" :value="2" />
                <el-option label="困难" :value="3" />
              </el-select>
            </el-form-item>
  
            <!-- 解析 -->
            <el-form-item label="答案解析" prop="analysis">
              <el-input
                v-model="editForm.analysis"
                type="textarea"
                :rows="3"
                placeholder="请输入答案解析"
              />
            </el-form-item>
  
            <!-- 知识点 -->
            <el-form-item label="知识点" prop="knowledgePoints">
              <el-select
                v-model="editForm.knowledgePoints"
                multiple
                filterable
                allow-create
                default-first-option
                class="form-select"
                placeholder="请输入或选择知识点"
              >
                <el-option
                  v-for="point in knowledgePointOptions"
                  :key="point"
                  :label="point"
                  :value="point"
                />
              </el-select>
            </el-form-item>
  
            <!-- 填空题答案 -->
            <template v-if="editForm.questionType === 'FILL_BLANK'">
              <el-form-item
                v-for="(_, index) in (editForm.blanks ? editForm.blanks.split('|') : [''])"
                :key="index"
                :label="'第' + (index + 1) + '空'"
                :prop="'blanks'"
              >
                <div class="blank-edit">
                  <el-input 
                    :model-value="editForm.blanks ? editForm.blanks.split('|')[index] : ''"
                    placeholder="请输入答案"
                    @update:model-value="(val) => handleBlankInput(val, index)" 
                  />
                  <el-button
                    type="danger"
                    circle
                    @click="removeBlank(index)"
                    :disabled="!editForm.blanks || editForm.blanks.split('|').length <= 1"
                    class="remove-btn"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" plain @click="addBlank">
                  添加填空
                </el-button>
              </el-form-item>
            </template>
  
            <!-- 综合题子题目 -->
            <template v-if="editForm.questionType === 'READING'">
              <el-form-item label="子题目">
                <div class="sub-questions-container">
                  <div v-for="(subQ, index) in editForm.subQuestions" :key="index" class="sub-question-edit">
                    <div class="sub-question-header">
                      <span class="sub-question-index">第{{ index + 1 }}小题</span>
                      <el-button
                        type="danger"
                        circle
                        @click="removeSubQuestion(index)"
                        :disabled="editForm.subQuestions.length <= 1"
                        class="remove-btn"
                      >
                        <el-icon><Delete /></el-icon>
                      </el-button>
                    </div>
                    
                    <el-form-item label="题目内容" :prop="'subQuestions.' + index + '.stem'">
                      <el-input
                        v-model="subQ.stem"
                        type="textarea"
                        :rows="2"
                        placeholder="请输入子题目内容"
                      />
                    </el-form-item>
                    
                    <!-- 子题目选项 -->
                    <template v-if="subQ.options && subQ.options.length > 0">
                      <el-form-item
                        v-for="(option, optIndex) in subQ.options"
                        :key="optIndex"
                        :label="'选项' + option.optionId"
                        :prop="'subQuestions.' + index + '.options.' + optIndex + '.content'"
                      >
                        <div class="option-edit">
                          <el-input v-model="option.content" placeholder="请输入选项内容" />
                          <el-button
                            type="danger"
                            circle
                            @click="removeSubOption(index, optIndex)"
                            :disabled="subQ.options.length <= 2"
                            class="remove-btn"
                          >
                            <el-icon><Delete /></el-icon>
                          </el-button>
                        </div>
                      </el-form-item>
                      <el-form-item>
                        <el-button
                          type="primary"
                          plain
                          @click="addSubOption(index)"
                          :disabled="subQ.options.length >= 6"
                        >
                          添加选项
                        </el-button>
                      </el-form-item>
                    </template>
                    
                    <el-form-item label="答案" :prop="'subQuestions.' + index + '.answer'">
                      <template v-if="subQ.options && subQ.options.length > 0">
                        <el-select v-model="subQ.answer" class="form-select">
                          <el-option
                            v-for="option in subQ.options"
                            :key="option.optionId"
                            :label="option.optionId"
                            :value="option.optionId"
                          />
                        </el-select>
                      </template>
                      <template v-else>
                        <el-input
                          v-model="subQ.answer"
                          type="textarea"
                          :rows="2"
                          placeholder="请输入答案"
                        />
                      </template>
                    </el-form-item>
                    
                    <el-form-item label="解析" :prop="'subQuestions.' + index + '.analysis'">
                      <el-input
                        v-model="subQ.analysis"
                        type="textarea"
                        :rows="2"
                        placeholder="请输入解析"
                      />
                    </el-form-item>
                    
                    <el-form-item label="分值" :prop="'subQuestions.' + index + '.score'">
                      <el-input-number
                        v-model="subQ.score"
                        :min="1"
                        :max="100"
                        controls-position="right"
                      />
                    </el-form-item>
                  </div>
                  
                  <div class="add-sub-question-btn">
                    <el-button type="primary" plain @click="addSubQuestion">
                      添加子题目
                    </el-button>
                  </div>
                </div>
              </el-form-item>
            </template>
          </el-form>
        </template>
  
        <template #footer>
          <div class="drawer-footer">
            <el-button @click="dialogVisible = false; disabled = true">取消</el-button>
            <el-button type="primary" @click="handleSave" :loading="saving">
              保存
            </el-button>
          </div>
        </template>
      </el-drawer>
    </div>
  </template>
  
  <script setup name="previewQuestion">
  import { ref, computed, onMounted, watch } from 'vue';
  import { Edit, Delete, Search, Plus, Document } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { useRoute } from 'vue-router'
  import { getLibraryQuestions, saveQuestions, updateQuestion,deleteQuestion } from '../../api/question'
  import { useQuestionIds } from '../../stores/counter'
  // 接收 previewQuestions 作为 props
    const props = defineProps({
    previewQuestions: {
        type: Array,
        default: () => []
    }
    })
  const route = useRoute()
  const selectValue = ref("all")
  const options = [{
    value: "all", 
    label: "全部题型"
  },{
    value: "SINGLE_CHOICE",
    label: "单选题"
  }, {
    value: "MULTIPLE_CHOICE",
    label: "多选题"
  }, {
    value: "TRUE_FALSE",
    label: "判断题" 
  }, {
    value: "FILL_BLANK",
    label: "填空题"
  }, {
    value: "SHORT_ANSWER",
    label: "简答题"
  }, {
    value: "READING",
    label: "综合题"
  }]
  const questionIds = useQuestionIds()
  const libraryId = ref(route.query.libraryId)
  const questions = ref([])
  // 使用 watch 监听 props.previewQuestions 的变化
watch(() => props.previewQuestions, (newQuestions) => {
  questions.value = newQuestions;
}, { immediate: true }); // immediate: true 确保初始值也被设置
  // 搜索关键词
  const searchKeyword = ref('')
  
  // 搜索处理函数
  const handleSearch = () => {
    // 如果搜索框为空，显示所有题目
    if (!searchKeyword.value.trim()) {
      return questions.value
    }
    
    // 根据关键词过滤题目
    return questions.value.filter(question => 
      question.stem.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      (question.analysis && question.analysis.toLowerCase().includes(searchKeyword.value.toLowerCase())) ||
      (question.knowledgePoints && question.knowledgePoints.some(point => 
        point.toLowerCase().includes(searchKeyword.value.toLowerCase())
      ))
    )
  }
  
  // 更新过滤后的题目列表计算属性
  const filteredQuestions = computed(() => {
    let filtered = questions.value
    
    // 先按搜索关键词过滤
    if (searchKeyword.value.trim()) {
      filtered = handleSearch()
    }
    
    // 再按题型过滤
    if (selectValue.value !== 'all') {
      filtered = filtered.filter(q => q.questionType === selectValue.value)
    }
    
    return filtered
  })
  
  // 获取题目类型标签样式
  const getQuestionTypeTag = (type) => {
    const typeMap = {
      'SINGLE_CHOICE': 'primary',
      'MULTIPLE_CHOICE': 'success',
      'TRUE_FALSE': 'info',
      'FILL_BLANK': 'warning',
      'SHORT_ANSWER': 'danger',
      'READING': 'danger' 
    }
    return typeMap[type] || 'info'
  }
  
  // 获取题目类型标签文本
  const getQuestionTypeLabel = (type) => {
    const typeMap = {
      'SINGLE_CHOICE': '单选题',
      'MULTIPLE_CHOICE': '多选题',
      'TRUE_FALSE': '判断题',
      'FILL_BLANK': '填空题',
      'SHORT_ANSWER': '简答题',
      'READING': '综合题'
    }
    return typeMap[type] || type
  }
  
  // 获取难度标签
  const getDifficultyTag = (difficulty) => {
    const difficultyMap = {
      1: 'success',
      2: 'warning',
      3: 'danger'
    }
    return difficultyMap[difficulty] || 'info'
  }
  
  // 获取难度标签文本
  const getDifficultyLabel = (difficulty) => {
    const difficultyMap = {
      1: '简单',
      2: '中等',
      3: '困难'
    }
    return difficultyMap[difficulty] || '未知'
  }
  
  // 导出状态
  const exporting = ref(false)
  
  // 获取题目列表
  const getQuestionDetail = async () => {
    try {
      const res = await getLibraryQuestions(libraryId.value)
      questions.value = res.data
    } catch (error) {
      console.error('获取题目失败:', error)
      ElMessage.error('获取题目失败，请重试')
    }
  }
  
  // 筛选题目
  const filterQuestions = () => {
    // 触发computed重新计算
    console.log('筛选类型:', selectValue.value)
  }
  
  // 导出Word文档
  const exportToWord = async () => {
    try {
      exporting.value = true
      
      // 准备导出数据
      const exportData = filteredQuestions.value.map((question, index) => {
        let questionText = `${index + 1} `
        
        // 根据题型添加标题
        switch(question.questionType) {
          case 'SINGLE_CHOICE':
            questionText += '[单选题] '
            break
          case 'MULTIPLE_CHOICE':
            questionText += '[多选题] '
            break
          case 'TRUE_FALSE':
            questionText += '[判断题] '
            break
          case 'FILL_BLANK':
            questionText += '[填空题] '
            break
          case 'SHORT_ANSWER':
            questionText += '[简答题] '
            break
          case 'READING':
            questionText += '[综合题] '
            break
        }
        
        // 根据不同题型处理内容
        if (question.questionType === 'READING') {
          // 综合题题先显示文章内容
          questionText += `\n${question.passage}\n\n`
          
          // 处理子题目
          if (question.subQuestions && question.subQuestions.length > 0) {
            question.subQuestions.forEach((subQ, subIndex) => {
              questionText += `(${subQ.score}分) 第${subIndex + 1}小题：${subQ.stem}\n`
              
              // 如果子题目有选项
              if (subQ.options && subQ.options.length > 0) {
                subQ.options.forEach(option => {
                  questionText += `${option.optionId}. ${option.content}\n`
                })
              }
              
              questionText += `答案：${subQ.answer}\n`
              if (subQ.analysis) {
                questionText += `解析：${subQ.analysis}\n`
              }
              questionText += '\n'
            })
          }
        } else if (question.questionType === 'FILL_BLANK') {
          // 填空题处理
          questionText += `${question.stem}\n`
          if (question.blanks) {
            const blanks = question.blanks.split('|')
            blanks.forEach((blank, blankIndex) => {
              questionText += `第${blankIndex + 1}空：${blank}\n`
            })
          }
        } else {
          // 其他题型处理
          questionText += question.stem + '\n'
          
          // 添加选项
          if (question.options && question.options.length > 0) {
            question.options.forEach(option => {
              questionText += `${option.optionId}. ${option.content}\n`
            })
          }
          
          // 添加答案
          questionText += '答案：'
          if (question.questionType === 'SINGLE_CHOICE') {
            questionText += question.answer
          } else if (question.questionType === 'MULTIPLE_CHOICE') {
            questionText += question.answers?.[0] || ''
          } else if (question.questionType === 'TRUE_FALSE') {
            questionText += question.answer === 'TRUE' ? '对' : '错'
          } else {
            questionText += question.answers?.[0] || question.answer || ''
          }
          questionText += '\n'
        }
        
        // 添加难度
        questionText += `难易程度：${getDifficultyLabel(question.difficulty)}\n`
        
        // 添加解析
        if (question.analysis && question.questionType !== 'READING') {
          questionText += `答案解析：${question.analysis}\n`
        }
        
        // 添加知识点
        if (question.knowledgePoints && question.knowledgePoints.length > 0) {
          questionText += `知识点：${question.knowledgePoints.join('；')}\n`
        }
        
        return questionText + '\n'
      }).join('\n')
      
      // 创建Blob对象
      const blob = new Blob([exportData], { type: 'application/msword;charset=utf-8' })
      
      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = `${route.query.libraryName}_${options.find(item => item.value === selectValue.value).label}.doc`
      
      // 触发下载
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      ElMessage.success('导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      ElMessage.error('导出失败，请重试')
    } finally {
      exporting.value = false
    }
  }
  
  // 编辑相关的数据
  const dialogVisible = ref(false)
  const editFormRef = ref(null)
  const editForm = ref({})
  const saving = ref(false)
  
  // 知识点选项（可以从后端获取或本地维护）
  const knowledgePointOptions = ref([
    '第一章:关键字',
    '第一章:类和对象',
    '第二章:数据类型',
    '第二章:数组',
    '第三章:基本数据类型',
    '第三章:引用数据类型',
    '面向对象:多态性'
  ])
  
  // 表单验证规则
  const rules = {
    questionType: [
      { required: true, message: '请选择题目类型', trigger: 'change' }
    ],
    stem: [
      { 
        required: true, 
        validator: (rule, value, callback) => {
          // 如果是综合题题，stem不是必填
          if (editForm.value.questionType === 'READING') {
            callback()
          } else if (!value) {
            callback(new Error('请输入题目内容'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    passage: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (editForm.value.questionType === 'READING' && !value) {
            callback(new Error('请输入阅读文章内容'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    answer: [
      {
        required: true,
        validator: (rule, value, callback) => {
          // 填空题和综合题题不需要验证answer字段
          if (['FILL_BLANK', 'READING'].includes(editForm.value.questionType)) {
            callback()
          } else if (!value && !editForm.value.answers?.[0]) {
            callback(new Error('请选择或输入答案'))
          } else {
            callback()
          }
        },
        trigger: 'change'
      }
    ],
    blanks: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (editForm.value.questionType === 'FILL_BLANK') {
            if (!editForm.value.blanks) {
              callback(new Error('请至少添加一个填空答案'))
            } else {
              const blanks = editForm.value.blanks.split('|')
              if (blanks.some(blank => !blank.trim())) {
                callback(new Error('填空答案不能为空'))
              } else {
                callback()
              }
            }
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    subQuestions: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (editForm.value.questionType === 'READING') {
            if (!editForm.value.subQuestions || editForm.value.subQuestions.length === 0) {
              callback(new Error('请至少添加一个子题目'))
            } else {
              // 验证每个子题目
              const invalidSubQuestion = editForm.value.subQuestions.find(subQ => {
                return !subQ.stem || !subQ.answer || !subQ.score ||
                  (subQ.options && subQ.options.length > 0 && subQ.options.some(opt => !opt.content))
              })
              
              if (invalidSubQuestion) {
                callback(new Error('请完善子题目的所有必填信息'))
              } else {
                callback()
              }
            }
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ],
    difficulty: [
      { required: true, message: '请选择难度', trigger: 'change' }
    ]
  }
  
  // 处理编辑按钮点击
  const handleEdit = (question) => {
    editForm.value = JSON.parse(JSON.stringify(question)) // 深拷贝
    if (editForm.value.questionType === 'MULTIPLE_CHOICE' && editForm.value.answers && editForm.value.answers[0]) {
      editForm.value.answers_tmp = editForm.value.answers[0].split(',')
    }
    // 确保填空题的blanks是字符串
    if (editForm.value.questionType === 'FILL_BLANK' && !editForm.value.blanks) {
      editForm.value.blanks = ''
    }
    dialogVisible.value = true
  }
  // 处理删除按钮点击
  const handleDelete = async (question) => {
    const res = await deleteQuestion(question.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      questionIds.deleteQuestionIds(question.id)
      questions.value = questions.value.filter(q => q.id !== question.id)
      // getQuestionDetail()
    } else {
      ElMessage.error('删除失败')
    }
  } 
  // 处理新增按钮点击
  const disabled = ref(true)
  const handleAdd = () => {
    disabled.value = false
    dialogVisible.value = true
    editForm.value = {
      id: '',
      stem: '',
      options: [],
      answers: [],
      analysis: '',
      knowledgePoints: [],
      difficulty: 1,
      questionType: 'SINGLE_CHOICE',
      blanks: '', // 初始化为空字符串
      answer: null,
      passage: null,
      subQuestions: null
    }
  }
  
  // 添加选项
  const addOption = () => {
    const newOptionId = String.fromCharCode(65 + editForm.value.options.length) // 生成新的选项ID (A, B, C...)
    editForm.value.options.push({
      optionId: newOptionId,
      content: ''
    })
  }
  
  // 删除选项
  const removeOption = (index) => {
    editForm.value.options.splice(index, 1)
    // 重新排序选项ID
    editForm.value.options.forEach((option, idx) => {
      option.optionId = String.fromCharCode(65 + idx)
    })
  }
  
  // 处理多选题答案变化
  const   handleMultipleAnswerChange = (value) => {
    editForm.value.answers_tmp = value
    editForm.value.answers[0] = editForm.value.answers_tmp.join(',')
  }
  
  // 保存题目
  const handleSave = async () => {
    if (!editFormRef.value) return
    
    await editFormRef.value.validate(async (valid) => {
      if (valid) {
        try {
          saving.value = true
          
          // 如果是更新操作
          if (editForm.value.id) {
            const data = JSON.stringify(editForm.value)
            console.log(data)
            await updateQuestion(editForm.value.id, data)
            ElMessage.success('更新成功')
            
            // 更新本地数据
            const index = questions.value.findIndex(q => q.id === editForm.value.id)
            if (index !== -1) {
              questions.value[index] = { ...editForm.value }
            }
          } 
          // 如果是新增操作
          else {
            const res = await saveQuestions(libraryId.value, JSON.stringify([editForm.value]))
            if (res.data && res.data.length > 0) {
              editForm.value.id = res.data[0]
              questionIds.addQuestionIds(res.data[0])
              questions.value.push({ ...editForm.value })
            }
            ElMessage.success('保存成功')
          }
          
          dialogVisible.value = false
        } catch (error) {
          console.error('保存失败:', error)
          ElMessage.error(error.message || '保存失败，请重试')
        } finally {
          saving.value = false
          disabled.value = true
        }
      }
    })
  }
  
  // 在script部分添加以下方法
  const formatFillBlankStem = (stem) => {
    if (!stem) return '';
    // 将下划线替换为更明显的填空标记
    return stem.replace(/_+/g, '________');
  };
  
  // 添加填空
  const addBlank = () => {
    if (!editForm.value.blanks) {
      editForm.value.blanks = ''
    }
    editForm.value.blanks = editForm.value.blanks ? editForm.value.blanks + '|' : ''
  }
  
  // 删除填空
  const removeBlank = (index) => {
    const blanks = editForm.value.blanks.split('|')
    blanks.splice(index, 1)
    editForm.value.blanks = blanks.join('|')
  }
  
  // 添加子题目
  const addSubQuestion = () => {
    if (!editForm.value.subQuestions) {
      editForm.value.subQuestions = []
    }
    editForm.value.subQuestions.push({
      stem: '',
      options: [],
      answer: '',
      analysis: '',
      score: 5
    })
  }
  
  // 删除子题目
  const removeSubQuestion = (index) => {
    editForm.value.subQuestions.splice(index, 1)
  }
  
  // 添加子题目选项
  const addSubOption = (subQuestionIndex) => {
    const subQ = editForm.value.subQuestions[subQuestionIndex]
    const newOptionId = String.fromCharCode(65 + subQ.options.length)
    subQ.options.push({
      optionId: newOptionId,
      content: ''
    })
  }
  
  // 删除子题目选项
  const removeSubOption = (subQuestionIndex, optionIndex) => {
    const subQ = editForm.value.subQuestions[subQuestionIndex]
    subQ.options.splice(optionIndex, 1)
    // 重新排序选项ID
    subQ.options.forEach((option, idx) => {
      option.optionId = String.fromCharCode(65 + idx)
    })
  }
  
  // 修改handleBlankInput方法
  const handleBlankInput = (value, index) => {
    const blanks = editForm.value.blanks ? editForm.value.blanks.split('|') : []
    blanks[index] = value
    editForm.value.blanks = blanks.join('|')
  }
  
  onMounted(() => {
    // getQuestionDetail()
  })
  </script>
  
  <style scoped>
  .question-detail-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .breadcrumb {
    margin-bottom: 20px;
    padding: 10px 0;
  }
  
  .top-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    gap: 20px;
  }
  
  .left-actions {
    display: flex;
    gap: 10px;
    align-items: center;
  }
  
  .search-box {
    max-width: 300px;
    min-width: 200px;
  }
  
  .search-input {
    width: 100%;
  }
  
  .filter-select {
    width: 120px;
  }
  
  .questions-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  
  .question-card {
    border-radius: 8px;
    transition: all 0.3s ease;
  }
  
  .question-card:hover {
    transform: translateY(-2px);
  }
  
  .question-header {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    gap: 12px;
  }
  
  .question-index {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
  
  .question-type-tag {
    margin-right: 8px;
  }
  
  .difficulty-tag {
    font-size: 12px;
  }
  
  .question-content {
    margin-bottom: 20px;
  }
  
  .question-stem {
    font-size: 15px;
    line-height: 1.6;
    color: #333;
    margin-bottom: 16px;
  }
  
  .options-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .option-item {
    display: flex;
    gap: 8px;
    padding: 8px 12px;
    border-radius: 4px;
    background-color: #f5f7fa;
    transition: background-color 0.3s ease;
  }
  
  .option-item:hover {
    background-color: #e6e8eb;
  }
  
  .option-id {
    font-weight: bold;
    color: #409EFF;
  }
  
  .true-false-options {
    margin-top: 12px;
  }
  
  .fill-blank-content {
    margin: 16px 0;
  }
  
  .fill-blank-stem {
    font-size: 15px;
    line-height: 1.6;
    margin-bottom: 16px;
    padding: 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
  
  .fill-blank-answers {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .blank-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
  
  .blank-index {
    font-weight: bold;
    color: #409EFF;
    margin-right: 8px;
  }
  
  .blank-answer {
    color: #67c23a;
  }
  
  .answer-section {
    margin-top: 16px;
    border-top: 1px solid #ebeef5;
  }
  
  .answer-title {
    color: #409EFF;
    font-weight: bold;
  }
  
  .answer-content {
    padding: 16px;
    background-color: #f8f9fa;
    border-radius: 4px;
  }
  
  .answer-area {
    margin-bottom: 16px;
  }
  
  .analysis-area {
    margin-bottom: 16px;
    line-height: 1.6;
  }
  
  .knowledge-points {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
  }
  
  .knowledge-tag {
    margin-right: 8px;
  }
  
  .formatted-answer {
    white-space: pre-wrap;
    line-height: 1.6;
  }
  
  /* 响应式设计 */
  @media screen and (max-width: 768px) {
    .top-actions {
      flex-direction: column;
      gap: 12px;
    }
    
    .left-actions {
      width: 100%;
      flex-wrap: wrap;
    }
    
    .search-box {
      width: 100%;
      max-width: 100%;
    }
    
    .question-card {
      margin-bottom: 16px;
    }
  }
  
  /* 编辑图标样式 */
  .edit-icon {
    position: absolute;
    top: 16px;
    right: 32px;
    opacity: 0;
    transition: opacity 0.3s ease;
  }
  /* 删除图标样式 */
  .delete-icon {
    position: absolute;
    top: 16px;
    right: 16px;
    opacity: 0;
    transition: opacity 0.3s ease;
  }
  
  .question-card:hover .edit-icon {
    opacity: 1;
  }
  
  .edit-btn {
    font-size: 30px;
    color: #409EFF;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    transition: all 0.3s ease;
  }
  
  .edit-btn:hover {
    color: #66b1ff;
    background-color: #ecf5ff;
  }
  
  /* 删除按钮样式 */
  .delete-btn {
    font-size: 30px;
    color: #f56c6c;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    transition: all 0.3s ease;
  }
  
  .delete-btn:hover {
    color: #f56c6c;
    background-color:  #ecf5ff;
  }
  
  /* 抽屉样式 */
  .edit-drawer {
    :deep(.el-drawer__header) {
      margin-bottom: 0;
      padding: 16px 20px;
      border-bottom: 1px solid #dcdfe6;
    }
  
    :deep(.el-drawer__body) {
      padding: 20px;
      overflow-y: auto;
    }
  
    :deep(.el-form) {
      height: calc(100vh - 170px);
      overflow-y: auto;
      padding-right: 16px;
    }
  }
  
  .drawer-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px 20px;
    background: #fff;
    border-top: 1px solid #dcdfe6;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
  
  /* 修改表单内部的滚动条样式 */
  .edit-form::-webkit-scrollbar {
    width: 6px;
  }
  
  .edit-form::-webkit-scrollbar-thumb {
    background-color: #dcdfe6;
    border-radius: 3px;
  }
  
  .edit-form::-webkit-scrollbar-track {
    background-color: #f5f7fa;
  }
  
  /* 综合题题样式 */
  .reading-passage {
    margin-bottom: 24px;
  }
  
  .passage-content {
    font-size: 15px;
    line-height: 1.8;
    padding: 16px;
    background-color: #f5f7fa;
    border-radius: 4px;
    margin-bottom: 20px;
    white-space: pre-wrap;
  }
  
  .sub-questions {
    display: flex;
    flex-direction: column;
    gap: 24px;
  }
  
  .sub-question {
    padding: 16px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
  
  .sub-question-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    gap: 8px;
  }
  
  .sub-question-index {
    font-weight: bold;
    color: #409EFF;
  }
  
  .sub-question-score {
    color: #f56c6c;
  }
  
  .sub-question-stem {
    font-size: 14px;
    line-height: 1.6;
    margin-bottom: 12px;
  }
  
  .sub-question-options {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  .sub-question-answer {
    margin-bottom: 12px;
  }
  
  .sub-question-analysis {
    margin-bottom: 12px;
  }
  
  .sub-question-title {
    font-weight: bold;
    color: #409EFF;
    margin-bottom: 4px;
  }
  
  .sub-question-content {
    padding-left: 16px;
  }
  
  .blank-answer-item {
    margin-bottom: 8px;
    color: #67c23a;
  }
  
  /* 响应式样式补充 */
  @media screen and (max-width: 768px) {
    .passage-content {
      padding: 12px;
    }
  
    .sub-question {
      padding: 12px;
    }
  }
  
  /* 编辑对话框中的填空题和综合题题样式 */
  .blank-edit {
    display: flex;
    gap: 12px;
    align-items: center;
  }
  
  .option-edit {
    display: flex;
    gap: 12px;
    align-items: center;
  }
  
  .option-edit .el-input {
    flex: 1;
  }
  
  .remove-btn {
    flex-shrink: 0;
  }
  
  .sub-question-edit {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 16px;
    margin-bottom: 16px;
  }
  
  .sub-question-edit .sub-question-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .sub-question-edit .sub-question-index {
    font-size: 16px;
    font-weight: bold;
    color: #409EFF;
  }
  
  .sub-question-edit .el-form-item {
    margin-bottom: 16px;
  }
  
  /* 响应式样式补充 */
  @media screen and (max-width: 768px) {
    .sub-question-edit {
      padding: 12px;
    }
  }
  
  /* 综合题子题目容器样式 */
  .sub-questions-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  .add-sub-question-btn {
    display: flex;
    justify-content: center;
    padding: 16px 0;
    border-top: 1px dashed #dcdfe6;
    margin-top: 8px;
  }
  </style>